import { SocketService } from './socket.service'
import { Injectable } from '@nestjs/common'
import * as WebSocket from 'ws'
import { OsService } from '../../../framework'
@Injectable()
export class SocketManager {
  sockets: WebSocket.Server[] = []
  constructor(private socketService: SocketService, private os: OsService) {}

  getMine(port: number) {
    const host = this.os.ipv4.address
  }

  async bootstrap() {
    // 初始化
    const host = this.os.ipv4.address
    const port = 6003
    const exist = await this.socketService.findOne({
      host,
      port
    })
    if (!exist) {
      await this.addSocket({ host, port })
    }
    const list = await this.socketService.getList()
    for (let key in list) {
      const res = list[key]
      await this.addSocket({ port: res.port, host: res.host })
    }
    return { host, port }
  }

  async addSocket({ port, host }) {
    this.sockets.push(await this.socketService.create(host, port))
  }

  // 群发
  broadcast(type, message) {
    this.sockets.forEach(socket => socket.emit(type, message))
  }
}
